package com.example.demo.service.impl;

import com.example.demo.service.EmailService;
import com.example.demo.utill.VerificationCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class EmailServiceImpl implements EmailService {
    VerificationCode verificationCode=new VerificationCode();
    private String code=verificationCode.verCode();
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private HttpServletRequest servletRequest;
    @Value("${spring.mail.username}")
    private String from;

    @Override
    public boolean sendSimpleMail(String email) {
        HttpSession session=servletRequest.getSession();
        try {
            session.setAttribute("code",code);
            SimpleMailMessage sm=new SimpleMailMessage();
            sm.setFrom(from);
            sm.setTo(email);
            sm.setSubject("在线书城");
            sm.setText("欢迎注册在线商城账户，您的验证码为:"+code);
            javaMailSender.send(sm);
            return true;
        } catch (MailException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean sendHtmlMail(String email) {
        MimeMessage message=javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper=new MimeMessageHelper(message,true);
            messageHelper.setFrom(from);
            messageHelper.setTo(email);
            message.setSubject("在线书城邮箱");
            messageHelper.setText("欢迎注册在线邮箱，您的验证码为:"+code,true);
            javaMailSender.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean sendAttachmentsMail(String email) {
        return false;
    }
}
